package Util;

import Util.ScanUtil;
import Util.HandlerDefinition;
import anntation.Mapping;
import interceprtor.Interceptor;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class HandlerDefinitionparse {
    private static List<String> className=ScanUtil.scanPackage();
    public static   Map<String, HandlerDefinition> map= new HashMap<String, HandlerDefinition>();
    public static  Map<String, HandlerDefinition> parse(){
        for (String classname: className){
            Class<?> clazz = createClazz(classname);
            if(clazz.isInterface()) continue;
            Method[] declaredMethods = clazz.getDeclaredMethods();
            for (Method method:declaredMethods){
                if (method.isAnnotationPresent(Mapping.class)){
                    HandlerDefinition definition = definition(clazz, method);
                    String name = getString(method);
                    map.put("/"+name,definition);
                }
            }
        }
        return map;
    }
    public static List<Interceptor> getInterceptor() {
        List<Interceptor> list = new ArrayList<>();
        for (String s : className) {
            Class<?> clazz = createClazz(s);
            try {
                /*if (clazz.newInstance() instanceof Interceptor) {
                    list.add((Interceptor) clazz.newInstance());
                }*/
                if (Interceptor.class.isInstance(clazz)&&!clazz.isInterface()){
                    list.add((Interceptor) clazz.newInstance());
                }
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return list;
    }
    private static String getString(Method method) {
        String name=null;
        if ("".equals(method.getAnnotation(Mapping.class).value())){
            name = method.getName();
        }else {
            name=method.getAnnotation(Mapping.class).value();
        }
        return name;
    }

    public static Class<?> createClazz(String name){
        Class<?> clazz=null;
        try {
            clazz=Class.forName(name);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return clazz;
    }
    public static HandlerDefinition definition(Class<?> clazz,Method method){
        HandlerDefinition handlerDefinition=new HandlerDefinition();
        handlerDefinition.setClazz(clazz);
        handlerDefinition.setMethod(method);
        return handlerDefinition;
    }
}
